import React from 'react'
import { View, TouchableOpacity, Text, ScrollView, Image, Modal, AsyncStorage,Platform } from 'react-native'

import Config from '../../config'
import SizeUtils from '../../common/SizeUtils'
import BasePage from '../common/BasePage'
import ToastUtils from '../../common/ToastUtils'
import DataManager from '../../datas/DataManager'
import Constants from '../../common/Constants'
import HeartLovePutMediaAction from '../../actions/heart/HeartLovePutMediaAction'
import HeartLoveGetMediaAction from '../../actions/heart/HeartLoveGetMediaAction'

const IMAGE_SCALE = 0.3
const IMAGE_MAX_SIZE = 800 //K
const Tabs = ['照片', '视频']
export default class HeartLovePage extends BasePage {
  constructor(props) {
    super(props)
    // this.state.isRefreshing = false;
    this._pageWidth = SizeUtils.getWindowSize().width
    this._pageHeight = SizeUtils.getWindowSize().height - Config.paddingTop

    //控件
    this._imagePicker = require('react-native-image-picker')
    //是否在选择图片
    this._isSelectedingImage = false

    this.state.photos = []
    this.state.videos = []

    this.state.msgData = 0
    this.state.selectIndex = 0
    this.state.buttonRect = {}
    this.state.isVisible = false
    this.state.showdisclamer = true
    this.state.currentIndex = 0
  }
  componentDidMount() {
    this._requestData()
  }

  _requestData() {
    new HeartLoveGetMediaAction().call(this)
  }

  render() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height,
          backgroundColor: '#ffffff',
          paddingTop: Config.paddingTop
        }}
      >
        {this._renderScrollView()}
        {this._renderNavigationBar()}
      </View>
    )
  }

  _renderScrollView() {
    return (
      <ScrollView
        style={{
          width: this._pageWidth,
          height: this._pageHeight
        }}
        ref={ref => (this._scrollView = ref)}
        horizontal={true} // 水平方向
        showsHorizontalScrollIndicator={false} // 水平指示器
        showsVerticalScrollIndicator={false} // 垂直指示器
        pagingEnabled={true} // 开启分页功能
        alwaysBounceHorizontal={false} //弹性拉动一截
        onScroll={this._onScroll.bind(this)}
        scrollEnabled={this.state.scrollEnabled}
      >
        {this._renderPhotoView()}
        {this._renderVideoView()}
      </ScrollView>
    )
  }

  _onScroll(event) {
    let x = event.nativeEvent.contentOffset.x
    let index = Math.round(x / this._pageWidth)
    if (this.state.currentIndex != index) {
      this.setState({
        currentIndex: index
      })
    }
  }

  doUpload() {
    console.log('开始上传单个图片 doUpload')
    if (this._imageData.type === 'local') {
      var key = Constants.RANDOM_UPLOAD_NAME(25) + this._imageData.response.fileName
      this.state.isUploadingImage = true
      DataManager.modelDic[Constants.MODULE_TYPE.ALI_OSS].uploadFile(
        key,
        this._imageData.response.uri,
        function(pre, res) {
          this.state.isUploadingImage = false
          console.log('单个图片上传完成 ', pre)
          if (pre === undefined || pre == null) {
            // callback(false)
            alert('上传失败')
          } else {
            let url = Config.aliUrl + pre + key
            const photos = this.state.photos
            const newPhotos = photos.slice()
            newPhotos.push(url)
            this.setState({ photos: newPhotos })

            const lover_id = this.props.pageData.routeData.lover_id
            new HeartLovePutMediaAction().call(this, {
              lover_id: lover_id,
              photos: newPhotos,
              videos: this.state.videos
            })
            console.log('单个图片上传完成 doUpload', url)
          }
        },
        this
      )
    } else {
      // callback(true, null);
    }
  }

  _selectImage() {
    if (this._isSelectedingImage) {
      return
    }
    var options = {
      title: '请选择',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '选择相册',
      quality: IMAGE_SCALE,
      storageOptions: {
        skipBackup: true,
        path: 'images'
      }
    }
    this._isSelectedingImage = true
    this._imagePicker.showImagePicker(options, response => {
      this._isSelectedingImage = false
      if (response.didCancel) {
        console.log('User cancelled image picker')
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error)
        try {
          ToastUtils.show('获取图片失败' + response.error + '!')
        } catch (e) {
          ToastUtils.show('获取图片失败!')
        }
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton)
      } else {
        console.log('获取成功')
        console.log(response)
        if (response.fileSize < IMAGE_MAX_SIZE * 1024) {
          ToastUtils.show('获取图片成功!')
          this._imageResponse = response
          this._imageData = {
            type: 'local',
            data: 'data:image/png;base64,' + this._imageResponse.data,
            response: this._imageResponse
          }
          this.doUpload()
        } else {
          ToastUtils.show('图片大小不能大于' + Math.floor(IMAGE_MAX_SIZE / IMAGE_SCALE) + 'k')
        }
      }
    })
  }

  _selectVideo = () => {
    if (this._isSelectedingImage) {
      return
    }
    var options = {
      title: '请选择',
      mediaType: 'video',
      videoQuality: 'low'
    }
    this._isSelectedingImage = true
    this._imagePicker.launchImageLibrary(options, response => {
      this._isSelectedingImage = false
      this.uploadVideoFile(Platform.OS === 'ios'? response.uri:response.path)
      /**
       * { path: '/storage/emulated/0/DCIM/Camera/VID_20180426_122030.mp4',
       * uri: 'content://com.google.android.apps.photos.contentprovider/-1/2/content%3A%2F%2Fmedia%2Fexternal%2Fvideo%2Fmedia%2F119/ORIGINAL/NONE/2020269555' }
       */
      console.log('showImagePicker-launchImageLibrary', response)
    })
  }

  uploadVideoFile = videoPath => {
    const fileName = videoPath.slice(videoPath.lastIndexOf('/') + 1)

    var key = Constants.RANDOM_UPLOAD_NAME(25) + fileName
    this.state.isUploadingImage = true
    DataManager.modelDic[Constants.MODULE_TYPE.ALI_OSS].uploadFile(
      key,
      videoPath,
      function(pre, res) {
        this.state.isUploadingImage = false
        if (pre === undefined || pre == null) {
          // callback(false)
          alert('上传失败')
        } else {
          let url = Config.aliUrl + pre + key
          const videos = this.state.videos
          const newVideos = videos.slice()
          newVideos.push({
            url:url,
            duration:1,
            pic:'',
          })
          this.setState({ videos: newVideos })

          const lover_id = this.props.pageData.routeData.lover_id
          console.log('单个视频上传完成 loveData', lover_id)
          new HeartLovePutMediaAction().call(this, {
            lover_id: lover_id,
            photos: this.state.photos,
            videos: newVideos
          })

          console.log('单个视频上传完成 doUpload', url)
        }
      },
      this
    )
  }

  _onUploadPress = index => {
    if (index === 0) {
      // 上传图片
      this._selectImage()
    } else {
      // 上传视频
      this._selectVideo()
    }
  }

  _renderUploadButton(index = 0) {
    const buttonText = index === 0 ? '上传照片' : '上传视频'
    return (
      <TouchableOpacity
        onPress={() => this._onUploadPress(index)}
        style={{
          position: 'absolute',
          bottom: 0,
          height: SizeUtils.translateDesignHeightToCode(90),
          width: this._pageWidth,
          backgroundColor: '#EE3535',
          alignItems: 'center',
          justifyContent: 'center'
        }}
      >
        <Text style={{ color: '#fff', fontSize: SizeUtils.translateFontSizeToCode(28) }}>{buttonText}</Text>
      </TouchableOpacity>
    )
  }

  _renderEmptyView(index = 0) {
    const emptySource =
      index === 0
        ? require('../../../resource/images/heart/empty_photo.png')
        : require('../../../resource/images/heart/empty_video.png')
    const desc = index === 0 ? '你还未发布任何照片哦,' : '你还未发布任何视频哦,'
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: this._pageHeight,
          alignItems: 'center',
          paddingTop: SizeUtils.translateDesignHeightToCode(280)
        }}
      >
        <Image
          style={{
            height: SizeUtils.translateDesignWidthToCode(200),
            width: SizeUtils.translateDesignWidthToCode(200)
          }}
          source={emptySource}
        />
        <Text style={{ fontSize: SizeUtils.translateFontSizeToCode(28), color: '#616161' }}>{desc}</Text>
        <Text style={{ fontSize: SizeUtils.translateFontSizeToCode(28), color: '#616161' }}>赶快上传一个吧~</Text>
        {this._renderUploadButton(index)}
      </View>
    )
  }

  _renderPhotoItem(imgSource) {
    return (
      <View
        key={imgSource}
        style={{
          height: SizeUtils.translateDesignHeightToCode(232),
          width: (this._pageWidth - SizeUtils.translateDesignWidthToCode(15 * 4)) / 3,
          marginLeft: SizeUtils.translateDesignWidthToCode(15),
          marginTop: SizeUtils.translateDesignWidthToCode(15),
          borderRadius: SizeUtils.translateDesignNumToCode(10)
        }}
      >
        <Image
          style={{
            height: SizeUtils.translateDesignHeightToCode(232),
            width: (this._pageWidth - SizeUtils.translateDesignWidthToCode(15 * 4)) / 3
          }}
          source={{ uri: imgSource }}
        />
        {/* <View style={{position:'absolute',bottom:0,height:SizeUtils.translateDesignHeightToCode(42),width:(this._pageWidth-SizeUtils.translateDesignWidthToCode(15*4))/3,alignItems:'center',justifyContent:'center'}}>
          <Text>删除</Text>
        </View> */}
      </View>
    )
  }

  _renderPhotoRow(photos, index) {
    return (
      <View style={{ flexDirection: 'row' }} key={`${index}`}>
        {photos.map(photo => this._renderPhotoItem(photo))}
      </View>
    )
  }

  _renderPhotoView() {
    if (this.state.photos.length === 0) {
      return this._renderEmptyView(0)
    }
    const newPhotos = this.chunk(this.state.photos, 3) // 二维数组
    console.log('_renderPhotoView', newPhotos)
    return (
      <View style={{ width: this._pageWidth, height: this._pageHeight }}>
        {newPhotos.map((photos, index) => this._renderPhotoRow(photos, index))}
        {this._renderUploadButton(0)}
      </View>
    )

    // return(<View style={{
    //   width: SizeUtils.getWindowSize().width,
    //   height: SizeUtils.getWindowSize().height,
    //   backgroundColor:'#f002',
    // }}/>)
  }

  _renderVideoItem(video) {
    const imgSource = `${video.url}?x-oss-process=video/snapshot,t_1,f_jpg,w_100,h_230,m_fast`
    return (
      <View
        key={video.url}
        style={{
          height: SizeUtils.translateDesignHeightToCode(232),
          width: (this._pageWidth - SizeUtils.translateDesignWidthToCode(15 * 4)) / 3,
          marginLeft: SizeUtils.translateDesignWidthToCode(15),
          marginTop: SizeUtils.translateDesignWidthToCode(15),
          borderRadius: SizeUtils.translateDesignNumToCode(10)
        }}
      >
        <Image
          style={{
            height: SizeUtils.translateDesignHeightToCode(232),
            width: (this._pageWidth - SizeUtils.translateDesignWidthToCode(15 * 4)) / 3
          }}
          source={{ uri: imgSource }}
        />
        {/* <View style={{position:'absolute',bottom:0,height:SizeUtils.translateDesignHeightToCode(42),width:(this._pageWidth-SizeUtils.translateDesignWidthToCode(15*4))/3,alignItems:'center',justifyContent:'center'}}>
            <Text>删除</Text>
          </View> */}
      </View>
    )
  }

  _renderVideoRow(videos, index) {
    return (
      <View style={{ flexDirection: 'row' }} key={`${index}`}>
        {videos.map(video => this._renderVideoItem(video))}
      </View>
    )
  }

  _renderVideoView() {
    const videos = this.state.videos
    if (videos.length === 0) {
      return this._renderEmptyView(1)
    }
    const vs = this.chunk(videos, 3) // 二维数组
    console.log('_renderPhotoView', vs)
    return (
      <View style={{ width: this._pageWidth, height: this._pageHeight }}>
        {vs.map((vss, index) => this._renderVideoRow(vss, index))}
        {this._renderUploadButton(1)}
      </View>
    )
    // return(<View style={{
    //   width: SizeUtils.getWindowSize().width,
    //   height: SizeUtils.getWindowSize().height,
    //   backgroundColor:'#0f02'
    // }}/>)
  }

  _renderNavigationBarTitle() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width / 2,
          height: SizeUtils.translateDesignHeightToCode(60),
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: '#0000'
        }}
      >
        {this._getButton(0)}
        {this._getButton(1)}
      </View>
    )
  }

  _onPressBtn(index) {
    this.setState(
      {
        scrollEnabled: true
      },
      () => this._scrollView.scrollTo({ x: index * this._pageWidth })
    )
  }

  _getButton(index) {
    return (
      <TouchableOpacity
        onPress={() => this._onPressBtn(index)}
        style={{
          width: SizeUtils.getWindowSize().width / 2 / Tabs.length,
          height: SizeUtils.translateDesignHeightToCode(60),
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center'
        }}
      >
        <View
          style={{
            height: SizeUtils.translateDesignHeightToCode(50),
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(30),
              color: '#fff'
            }}
          >
            {Tabs[index]}
          </Text>
        </View>
        <View
          style={{
            borderColor: '#fff',
            borderBottomWidth: index == this.state.currentIndex ? SizeUtils.translateDesignNumToCode(6) : 0,
            width: SizeUtils.translateDesignWidthToCode(60),
            height: SizeUtils.translateDesignHeightToCode(5)
          }}
        />
      </TouchableOpacity>
    )
  }

  chunk(array, size) {
    // #1
    size = Math.max(size, 0)
    const length = array == null ? 0 : array.length
    if (!length || size < 1) {
      return []
    }

    // #2
    let index = 0
    let resIndex = 0
    const result = new Array(Math.ceil(length / size))

    // #3
    while (index < length) {
      result[resIndex++] = array.slice(index, (index += size))
    }
    return result
  }
}
